<template>
  <div class="simple-rich-editor">
    <!-- 工具栏 -->
    <div class="editor-toolbar">
      <el-button-group>
        <el-button 
          size="small" 
          @click="insertHeading('h1')"
          :class="{ 'is-active': currentHeading === 'h1' }"
          title="一级标题 - 点击切换H1标题格式，再次点击可取消标题"
        >
          H1
        </el-button>
        <el-button 
          size="small" 
          @click="insertHeading('h2')"
          :class="{ 'is-active': currentHeading === 'h2' }"
          title="二级标题 - 点击切换H2标题格式，再次点击可取消标题"
        >
          H2
        </el-button>
        <el-button 
          size="small" 
          @click="insertHeading('h3')"
          :class="{ 'is-active': currentHeading === 'h3' }"
          title="三级标题 - 点击切换H3标题格式，再次点击可取消标题"
        >
          H3
        </el-button>
      </el-button-group>
      
      <el-divider direction="vertical" />
      
      <el-button-group>
        <el-button 
          size="small" 
          @click="toggleBold"
          :class="{ 'is-active': isBold }"
          title="加粗 - 点击切换加粗格式，再次点击可取消加粗"
        >
          <strong>B</strong>
        </el-button>
        <el-button 
          size="small" 
          @click="toggleItalic"
          :class="{ 'is-active': isItalic }"
          title="斜体 - 点击切换斜体格式，再次点击可取消斜体"
        >
          <em>I</em>
        </el-button>
        <el-button 
          size="small" 
          @click="toggleUnderline"
          :class="{ 'is-active': isUnderline }"
          title="下划线 - 点击切换下划线格式，再次点击可取消下划线"
        >
          <u>U</u>
        </el-button>
      </el-button-group>
      
      <el-divider direction="vertical" />
      
      <el-button-group>
        <el-button 
          size="small" 
          @click="setAlignment('left')"
          :class="{ 'is-active': currentAlignment === 'left' }"
          title="左对齐 - 点击切换左对齐，再次点击可重置为左对齐"
        >
          <i class="el-icon-s-fold">《</i>
        </el-button>
        <el-button 
          size="small" 
          @click="setAlignment('center')"
          :class="{ 'is-active': currentAlignment === 'center' }"
          title="居中对齐 - 点击切换居中对齐，再次点击可重置为左对齐"
        >
          <i class="el-icon-s-operation">^</i>
        </el-button>
        <el-button 
          size="small" 
          @click="setAlignment('right')"
          :class="{ 'is-active': currentAlignment === 'right' }"
          title="右对齐 - 点击切换右对齐，再次点击可重置为左对齐"
        >
          <i class="el-icon-s-unfold">》</i>
        </el-button>
      </el-button-group>
      
      <el-divider direction="vertical" />
      
      <el-button-group>
        <el-button 
          size="small" 
          @click="insertList('ul')"
          :class="{ 'is-active': isInList('ul') }"
          title="无序列表 - 点击切换无序列表格式，再次点击可取消列表"
        >
          •
        </el-button>
        <el-button 
          size="small" 
          @click="insertList('ol')"
          :class="{ 'is-active': isInList('ol') }"
          title="有序列表 - 点击切换有序列表格式，再次点击可取消列表"
        >
          1.
        </el-button>
      </el-button-group>
      
      <el-divider direction="vertical" />
      
      <!-- <el-button 
        size="small" 
        @click="insertLink"
        title="插入链接"
      >
        链接
      </el-button>
      
      <el-button 
        size="small" 
        @click="insertTable"
        title="插入表格"
      >
        表格
      </el-button> -->
    </div>
    
    <!-- 编辑区域 -->
    <div 
      ref="editorRef"
      class="editor-content"
      contenteditable="true"
      @input="handleInput"
      @paste="handlePaste"
      @keydown="handleKeydown"
      @mouseup="updateFormatState"
      @keyup="updateFormatState"
    ></div>
    
    <!-- 链接输入对话框 -->
    <el-dialog v-model="showLinkDialog" title="插入链接" width="400px">
      <el-form :model="linkForm" label-width="80px">
        <el-form-item label="链接文本">
          <el-input v-model="linkForm.text" placeholder="请输入链接文本" />
        </el-form-item>
        <el-form-item label="链接地址">
          <el-input v-model="linkForm.url" placeholder="请输入链接地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showLinkDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmInsertLink">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 表格插入对话框 -->
    <el-dialog v-model="showTableDialog" title="插入表格" width="400px">
      <el-form :model="tableForm" label-width="80px">
        <el-form-item label="行数">
          <el-input-number v-model="tableForm.rows" :min="1" :max="20" />
        </el-form-item>
        <el-form-item label="列数">
          <el-input-number v-model="tableForm.cols" :min="1" :max="20" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showTableDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmInsertTable">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请输入内容...'
  }
})

// Emits
const emit = defineEmits(['update:modelValue'])

// 响应式数据
const editorRef = ref(null)
const showLinkDialog = ref(false)
const showTableDialog = ref(false)
const linkForm = ref({ text: '', url: '' })
const tableForm = ref({ rows: 3, cols: 3 })

// 格式状态检测
const isBold = ref(false)
const isItalic = ref(false)
const isUnderline = ref(false)
const currentAlignment = ref('left')
const currentHeading = ref('')
const isInUnorderedList = ref(false)
const isInOrderedList = ref(false)

// 方法
const handleInput = () => {
  const content = editorRef.value.innerHTML
  emit('update:modelValue', content)
  // 检测当前格式状态
  updateFormatState()
}

// 检测当前格式状态
const updateFormatState = () => {
  const selection = window.getSelection()
  if (selection.rangeCount > 0) {
    const range = selection.getRangeAt(0)
    const container = range.commonAncestorContainer
    
    // 检测文本格式
    isBold.value = document.queryCommandState('bold')
    isItalic.value = document.queryCommandState('italic')
    isUnderline.value = document.queryCommandState('underline')
    
    // 检测对齐方式
    const parentElement = container.nodeType === Node.TEXT_NODE ? container.parentElement : container
    if (parentElement) {
      const textAlign = window.getComputedStyle(parentElement).textAlign
      currentAlignment.value = textAlign || 'left'
    }
    
    // 检测标题
    let heading = ''
    let current = parentElement
    while (current && current !== editorRef.value) {
      if (current.tagName && ['H1', 'H2', 'H3'].includes(current.tagName)) {
        heading = current.tagName.toLowerCase()
        break
      }
      current = current.parentElement
    }
    currentHeading.value = heading
    
    // 检测列表
    let currentList = parentElement
    while (currentList && currentList !== editorRef.value) {
      if (currentList.tagName === 'UL') {
        isInUnorderedList.value = true
        isInOrderedList.value = false
        break
      } else if (currentList.tagName === 'OL') {
        isInOrderedList.value = true
        isInUnorderedList.value = false
        break
      }
      currentList = currentList.parentElement
    }
    
    // 如果没有在列表中，重置列表状态
    if (!isInUnorderedList.value && !isInOrderedList.value) {
      isInUnorderedList.value = false
      isInOrderedList.value = false
    }
  }
}

// 检查是否在指定类型的列表中
const isInList = (type) => {
  return type === 'ul' ? isInUnorderedList.value : isInOrderedList.value
}

// 简单的光标位置保存和恢复
const saveSelection = () => {
  const selection = window.getSelection()
  if (selection.rangeCount > 0) {
    const range = selection.getRangeAt(0)
    return {
      startContainer: range.startContainer,
      startOffset: range.startOffset,
      endContainer: range.endContainer,
      endOffset: range.endOffset
    }
  }
  return null
}

const restoreSelection = (savedSelection) => {
  if (savedSelection) {
    try {
      const selection = window.getSelection()
      const range = document.createRange()
      range.setStart(savedSelection.startContainer, savedSelection.startOffset)
      range.setEnd(savedSelection.endContainer, savedSelection.endOffset)
      selection.removeAllRanges()
      selection.addRange(range)
      return true
    } catch (error) {
      return false
    }
  }
  return false
}

const handlePaste = (e) => {
  e.preventDefault()
  const text = e.clipboardData.getData('text/plain')
  document.execCommand('insertText', false, text)
}

const handleKeydown = (e) => {
  // 处理Tab键
  if (e.key === 'Tab') {
    e.preventDefault()
    document.execCommand('insertText', false, '    ')
  }
  
  // 处理Enter键在列表中的行为
  if (e.key === 'Enter') {
    const selection = window.getSelection()
    if (selection.rangeCount > 0) {
      const range = selection.getRangeAt(0)
      const currentNode = range.startContainer
      const listItem = findParentListItem(currentNode)
      
      if (listItem) {
        e.preventDefault()
        handleEnterInList(listItem, range)
      }
    }
  }
  
  // 只在删除空段落时保持光标位置
  if (e.key === 'Backspace') {
    const selection = window.getSelection()
    if (selection.rangeCount > 0) {
      const range = selection.getRangeAt(0)
      const currentNode = range.startContainer
      
      // 检查是否在空段落中
      if (currentNode.nodeType === Node.TEXT_NODE && 
          currentNode.textContent === '' && 
          currentNode.parentNode && 
          currentNode.parentNode.tagName === 'P') {
        
        const savedSelection = saveSelection()
        setTimeout(() => {
          if (savedSelection) {
            restoreSelection(savedSelection)
          }
        }, 10)
      }
    }
  }
  

}

// 查找父级列表项
const findParentListItem = (node) => {
  let current = node
  while (current && current !== editorRef.value) {
    if (current.nodeType === Node.ELEMENT_NODE) {
      if (current.tagName === 'LI') {
        return current
      }
    }
    current = current.parentNode
  }
  return null
}

// 在列表中处理Enter键
const handleEnterInList = (listItem, range) => {
  const listContainer = listItem.parentNode
  const isOrdered = listContainer.tagName === 'OL'
  
  // 创建新的列表项
  const newLi = document.createElement('li')
  newLi.textContent = ''
  newLi.style.margin = '8px 0'
  newLi.style.paddingLeft = '8px'
  newLi.style.lineHeight = '1.6'
  
  // 在当前位置插入新列表项
  if (listItem.nextSibling) {
    listContainer.insertBefore(newLi, listItem.nextSibling)
  } else {
    listContainer.appendChild(newLi)
  }
  
  // 将光标放在新列表项中
  const newRange = document.createRange()
  const selection = window.getSelection()
  newRange.setStart(newLi, 0)
  newRange.collapse(true)
  selection.removeAllRanges()
  selection.addRange(range)
  
  handleInput()
}

const toggleBold = () => {
  const selection = window.getSelection()
  if (selection.rangeCount > 0) {
    const range = selection.getRangeAt(0)
    
    if (selection.toString().trim()) {
      // 如果有选中的文本，应用加粗格式
      document.execCommand('bold', false, null)
    } else {
      // 检查当前是否已经是加粗
      let currentNode = range.commonAncestorContainer
      if (currentNode.nodeType === Node.TEXT_NODE) {
        currentNode = currentNode.parentElement
      }
      
      // 向上查找加粗元素
      while (currentNode && currentNode !== editorRef.value) {
        if (currentNode.tagName === 'STRONG' || currentNode.tagName === 'B') {
          // 如果已经是加粗，则删除加粗标签，保留文本内容
          const textContent = currentNode.textContent
          const textNode = document.createTextNode(textContent)
          currentNode.parentNode.replaceChild(textNode, currentNode)
          
          // 将光标移到文本末尾
          const newRange = document.createRange()
          newRange.setStartAfter(textNode)
          newRange.collapse(true)
          selection.removeAllRanges()
          selection.addRange(newRange)
          
          editorRef.value.focus()
          handleInput()
          return
        }
        currentNode = currentNode.parentElement
      }
      
      // 如果没有选中文本且不是加粗，插入加粗的示例文本
      insertHTML('<strong>加粗文本</strong>')
    }
  }
  editorRef.value.focus()
  handleInput()
}

const toggleItalic = () => {
  const selection = window.getSelection()
  if (selection.rangeCount > 0) {
    const range = selection.getRangeAt(0)
    
    if (selection.toString().trim()) {
      // 如果有选中的文本，应用斜体格式
      document.execCommand('italic', false, null)
    } else {
      // 检查当前是否已经是斜体
      let currentNode = range.commonAncestorContainer
      if (currentNode.nodeType === Node.TEXT_NODE) {
        currentNode = currentNode.parentElement
      }
      
      // 向上查找斜体元素
      while (currentNode && currentNode !== editorRef.value) {
        if (currentNode.tagName === 'EM' || currentNode.tagName === 'I') {
          // 如果已经是斜体，则删除斜体标签，保留文本内容
          const textContent = currentNode.textContent
          const textNode = document.createTextNode(textContent)
          currentNode.parentNode.replaceChild(textNode, currentNode)
          
          // 将光标移到文本末尾
          const newRange = document.createRange()
          newRange.setStartAfter(textNode)
          newRange.collapse(true)
          selection.removeAllRanges()
          selection.addRange(newRange)
          
          editorRef.value.focus()
          handleInput()
          return
        }
        currentNode = currentNode.parentElement
      }
      
      // 如果没有选中文本且不是斜体，插入斜体的示例文本
      insertHTML('<em>斜体文本</em>')
    }
  }
  editorRef.value.focus()
  handleInput()
}

const toggleUnderline = () => {
  const selection = window.getSelection()
  if (selection.rangeCount > 0) {
    const range = selection.getRangeAt(0)
    
    if (selection.toString().trim()) {
      // 如果有选中的文本，应用下划线格式
      document.execCommand('underline', false, null)
    } else {
      // 检查当前是否已经有下划线
      let currentNode = range.commonAncestorContainer
      if (currentNode.nodeType === Node.TEXT_NODE) {
        currentNode = currentNode.parentElement
      }
      
      // 向上查找下划线元素
      while (currentNode && currentNode !== editorRef.value) {
        if (currentNode.tagName === 'U') {
          // 如果已经有下划线，则删除下划线标签，保留文本内容
          const textContent = currentNode.textContent
          const textNode = document.createTextNode(textContent)
          currentNode.parentNode.replaceChild(textNode, currentNode)
          
          // 将光标移到文本末尾
          const newRange = document.createRange()
          newRange.setStartAfter(textNode)
          newRange.collapse(true)
          selection.removeAllRanges()
          selection.addRange(newRange)
          
          editorRef.value.focus()
          handleInput()
          return
        }
        currentNode = currentNode.parentElement
      }
      
      // 如果没有选中文本且没有下划线，插入下划线的示例文本
      insertHTML('<u>下划线文本</u>')
    }
  }
  editorRef.value.focus()
  handleInput()
}

const insertHeading = (tag) => {
  try {
    const selection = window.getSelection()
    if (selection.rangeCount > 0) {
      const range = selection.getRangeAt(0)
      const selectedText = selection.toString().trim()
      
      // 检查当前是否已经是该标题
      let currentElement = range.commonAncestorContainer
      if (currentElement.nodeType === Node.TEXT_NODE) {
        currentElement = currentElement.parentElement
      }
      
      // 向上查找标题元素
      while (currentElement && currentElement !== editorRef.value) {
        if (currentElement.tagName && ['H1', 'H2', 'H3'].includes(currentElement.tagName)) {
          if (currentElement.tagName.toLowerCase() === tag) {
            // 如果已经是该标题，则删除标题标签，保留文本内容
            const textContent = currentElement.textContent
            const textNode = document.createTextNode(textContent)
            currentElement.parentNode.replaceChild(textNode, currentElement)
            
            // 将光标移到文本末尾
            const newRange = document.createRange()
            newRange.setStartAfter(textNode)
            newRange.collapse(true)
            selection.removeAllRanges()
            selection.addRange(newRange)
            
            editorRef.value.focus()
            handleInput()
            return
          } else {
            // 如果是其他标题，先删除旧标题
            const textContent = currentElement.textContent
            const textNode = document.createTextNode(textContent)
            currentElement.parentNode.replaceChild(textNode, currentElement)
            currentElement = textNode
          }
          break
        }
        currentElement = currentElement.parentElement
      }
      
      if (selectedText) {
        // 如果选中了文本，将其转换为标题
        const element = document.createElement(tag)
        element.textContent = selectedText
        
        try {
          range.deleteContents()
          range.insertNode(element)
          
          // 安全地设置光标位置
          try {
            range.setStart(element, 0)
            range.setEnd(element, element.textContent.length)
            selection.removeAllRanges()
            selection.addRange(range)
          } catch (error) {
            // 如果设置光标位置失败，将光标放在元素后面
            range.setStartAfter(element)
            range.collapse(true)
            selection.removeAllRanges()
            selection.addRange(range)
          }
        } catch (error) {
          // 如果插入失败，使用insertHTML方法
          const html = `<${tag}>${selectedText}</${tag}>`
          insertHTML(html)
        }
      } else {
        // 如果没有选中文本，插入一个可编辑的标题
        const element = document.createElement(tag)
        element.textContent = '点击编辑标题'
        element.contentEditable = true
        
        try {
          range.deleteContents()
          range.insertNode(element)
          
          // 将光标放在标题内，方便编辑
          range.setStart(element, 0)
          range.setEnd(element, element.textContent.length)
          selection.removeAllRanges()
          selection.addRange(range)
        } catch (error) {
          // 如果插入失败，使用insertHTML方法
          const html = `<${tag} contenteditable="true">点击编辑标题</${tag}>`
          insertHTML(html)
        }
      }
    } else {
      // 如果没有选择范围，在编辑器末尾插入一个可编辑的标题
      const html = `<${tag} contenteditable="true">点击编辑标题</${tag}>`
      insertHTML(html)
    }
    
    editorRef.value.focus()
    handleInput()
  } catch (error) {
    console.error('插入标题失败:', error)
    ElMessage.error('插入标题失败，请重试')
  }
}

const setAlignment = (align) => {
  const selection = window.getSelection()
  if (selection.rangeCount > 0) {
    const range = selection.getRangeAt(0)
    
    // 检查当前是否已经是该对齐方式
    let currentNode = range.commonAncestorContainer
    if (currentNode.nodeType === Node.TEXT_NODE) {
      currentNode = currentNode.parentElement
    }
    
    // 向上查找段落元素
    while (currentNode && currentNode !== editorRef.value) {
      if (currentNode.tagName === 'P' || currentNode.tagName === 'DIV' || 
          ['H1', 'H2', 'H3'].includes(currentNode.tagName)) {
        const currentAlign = window.getComputedStyle(currentNode).textAlign
        
        if (currentAlign === align) {
          // 如果已经是该对齐方式，则重置为左对齐
          currentNode.style.textAlign = 'left'
        } else {
          // 否则设置为新的对齐方式
          document.execCommand('justify' + align.charAt(0).toUpperCase() + align.slice(1), false, null)
        }
        break
      }
      currentNode = currentNode.parentElement
    }
  }
  
  editorRef.value.focus()
  handleInput()
}

const insertList = (type) => {
  const selection = window.getSelection()
  if (selection.rangeCount > 0) {
    const range = selection.getRangeAt(0)
    
    // 检查当前是否已经在列表中
    let currentNode = range.commonAncestorContainer
    if (currentNode.nodeType === Node.TEXT_NODE) {
      currentNode = currentNode.parentElement
    }
    
    // 向上查找列表容器
    let listContainer = null
    while (currentNode && currentNode !== editorRef.value) {
      if (currentNode.tagName === 'UL' || currentNode.tagName === 'OL') {
        listContainer = currentNode
        break
      }
      currentNode = currentNode.parentElement
    }
    
    // 如果已经在列表中，且点击的是相同类型的列表按钮，则删除列表标签
    if (listContainer) {
      if ((type === 'ul' && listContainer.tagName === 'UL') || 
          (type === 'ol' && listContainer.tagName === 'OL')) {
        // 删除列表标签，保留所有文本内容
        const listItems = listContainer.querySelectorAll('li')
        const textNodes = []
        
        listItems.forEach((li, index) => {
          const textContent = li.textContent
          const textNode = document.createTextNode(textContent)
          textNodes.push(textNode)
          
          // 如果不是最后一个项目，添加换行
          if (index < listItems.length - 1) {
            textNodes.push(document.createElement('br'))
          }
        })
        
        // 替换列表容器
        listContainer.parentNode.replaceChild(document.createDocumentFragment(), listContainer)
        textNodes.forEach(node => {
          listContainer.parentNode.insertBefore(node, listContainer.nextSibling)
        })
        
        // 将光标移到文本末尾
        const newRange = document.createRange()
        newRange.setStartAfter(textNodes[textNodes.length - 1])
        newRange.collapse(true)
        selection.removeAllRanges()
        selection.addRange(newRange)
        
        editorRef.value.focus()
        handleInput()
        return
      }
    }
    
    // 如果有选中的文本，将其转换为列表
    if (selection.toString().trim()) {
      const selectedText = selection.toString().trim()
      const listItems = selectedText.split('\n').filter(item => item.trim())
      
      if (listItems.length > 1) {
        // 多行文本，每行作为一个列表项
        let listHTML = type === 'ul' ? '<ul style="margin: 0; padding-left: 20px;">' : '<ol style="margin: 0; padding-left: 20px;">'
        listItems.forEach(item => {
          listHTML += `<li style="margin: 8px 0; padding-left: 8px;">${item.trim()}</li>`
        })
        listHTML += type === 'ul' ? '</ul>' : '</ol>'
        
        // 替换选中的文本
        range.deleteContents()
        insertHTML(listHTML)
      } else {
        // 单行文本，使用execCommand创建标准列表（会自动缩进）
        try {
          document.execCommand(type === 'ul' ? 'insertUnorderedList' : 'insertOrderedList', false, null)
        } catch (error) {
          // 如果execCommand失败，手动创建缩进列表
          const listHTML = type === 'ul' 
            ? '<ul style="margin: 0; padding-left: 20px;"><li style="margin: 8px 0; padding-left: 8px;">' + selectedText + '</li></ul>'
            : '<ol style="margin: 0; padding-left: 20px;"><li style="margin: 8px 0; padding-left: 8px;">' + selectedText + '</li></ol>'
          insertHTML(listHTML)
        }
      }
    } else {
      // 检查是否在现有列表中，如果是则添加新项目
      const currentNode = selection.anchorNode
      const listContainer = findParentList(currentNode)
      
      if (listContainer) {
        // 在现有列表中添加新项目
        addListItem(listContainer, type)
      } else {
        // 如果没有选中文本且不在列表中，插入示例列表
        const listHTML = type === 'ul' 
          ? '<ul style="margin: 0; padding-left: 20px;"><li style="margin: 8px 0; padding-left: 8px;">列表项1</li><li style="margin: 8px 0; padding-left: 8px;">列表项2</li><li style="margin: 8px 0; padding-left: 8px;">列表项3</li></ul>'
          : '<ol style="margin: 0; padding-left: 20px;"><li style="margin: 8px 0; padding-left: 8px;">列表项2</li><li style="margin: 8px 0; padding-left: 8px;">列表项3</li></ol>'
        insertHTML(listHTML)
      }
    }
  }
  editorRef.value.focus()
  handleInput()
}

// 查找父级列表容器
const findParentList = (node) => {
  let current = node
  while (current && current !== editorRef.value) {
    if (current.nodeType === Node.ELEMENT_NODE) {
      if (current.tagName === 'UL' || current.tagName === 'OL') {
        return current
      }
    }
    current = current.parentNode
  }
  return null
}

// 在现有列表中添加新项目
const addListItem = (listContainer, type) => {
  const newLi = document.createElement('li')
  newLi.textContent = '新列表项'
  newLi.style.margin = '8px 0'
  newLi.style.paddingLeft = '8px'
  newLi.style.lineHeight = '1.6'
  
  listContainer.appendChild(newLi)
  
  // 将光标放在新列表项中
  const range = document.createRange()
  const selection = window.getSelection()
  range.setStart(newLi, 0)
  range.setEnd(newLi, newLi.textContent.length)
  selection.removeAllRanges()
  selection.addRange(range)
  
  handleInput()
}

const insertLink = () => {
  const selection = window.getSelection()
  if (selection.toString()) {
    linkForm.value.text = selection.toString()
    linkForm.value.url = 'https://'
    showLinkDialog.value = true
  } else {
    ElMessage.warning('请先选择要添加链接的文本')
  }
}

// 改进的插入HTML方法
const insertHTML = (html) => {
  try {
    document.execCommand('insertHTML', false, html)
  } catch (error) {
    // 如果execCommand失败，使用更安全的方法
    const selection = window.getSelection()
    if (selection.rangeCount > 0) {
      const range = selection.getRangeAt(0)
      const tempDiv = document.createElement('div')
      tempDiv.innerHTML = html
      
      // 将HTML内容插入到光标位置
      const fragment = document.createDocumentFragment()
      while (tempDiv.firstChild) {
        fragment.appendChild(tempDiv.firstChild)
      }
      
      range.deleteContents()
      range.insertNode(fragment)
      
      // 将光标放在插入内容的后面
      range.setStartAfter(fragment.lastChild || fragment)
      range.collapse(true)
      selection.removeAllRanges()
      selection.addRange(range)
    } else {
      // 如果没有选择范围，在编辑器末尾插入
      if (editorRef.value) {
        editorRef.value.innerHTML += html
        // 将光标移到末尾
        const range = document.createRange()
        const selection = window.getSelection()
        range.selectNodeContents(editorRef.value)
        range.collapse(false)
        selection.removeAllRanges()
        selection.addRange(range)
      }
    }
  }
}

const confirmInsertLink = () => {
  if (!linkForm.value.text || !linkForm.value.url) {
    ElMessage.warning('请填写完整的链接信息')
    return
  }
  
  const link = `<a href="${linkForm.value.url}" target="_blank">${linkForm.value.text}</a>`
  insertHTML(link)
  showLinkDialog.value = false
  editorRef.value.focus()
  handleInput()
}

const insertTable = () => {
  showTableDialog.value = true
}

const confirmInsertTable = () => {
  const rows = tableForm.value.rows
  const cols = tableForm.value.cols
  
  let tableHTML = '<table border="1" style="border-collapse: collapse; width: 100%;">'
  
  for (let i = 0; i < rows; i++) {
    tableHTML += '<tr>'
    for (let j = 0; j < cols; j++) {
      tableHTML += '<td style="padding: 8px; border: 1px solid #ddd;">&nbsp;</td>'
    }
    tableHTML += '</tr>'
  }
  
  tableHTML += '</table>'
  
  insertHTML(tableHTML)
  showTableDialog.value = false
  editorRef.value.focus()
  handleInput()
}

// 监听modelValue变化 - 只在初始化时设置内容
watch(() => props.modelValue, (newValue, oldValue) => {
  // 只在组件初始化时设置内容，避免在编辑过程中干扰
  if (editorRef.value && !oldValue && newValue) {
    editorRef.value.innerHTML = newValue
  }
}, { immediate: true })

// 初始化编辑器
const initEditor = () => {
  if (editorRef.value && !editorRef.value.innerHTML.trim()) {
    // 如果编辑器为空，添加一个占位符段落
    editorRef.value.innerHTML = '<p><br></p>'
  }
  
  // 设置初始内容
  if (props.modelValue && editorRef.value.innerHTML !== props.modelValue) {
    editorRef.value.innerHTML = props.modelValue
  }
}

// 组件挂载后初始化
onMounted(() => {
  nextTick(() => {
    initEditor()
  })
})

// 暴露方法给父组件
defineExpose({
  focus: () => editorRef.value?.focus(),
  getContent: () => editorRef.value?.innerHTML || '',
  setContent: (content) => {
    if (editorRef.value) {
      editorRef.value.innerHTML = content
      emit('update:modelValue', content)
    }
  }
})
</script>

<style scoped>
.simple-rich-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.editor-toolbar {
  background-color: #f5f7fa;
  padding: 8px;
  border-bottom: 1px solid #dcdfe6;
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.editor-toolbar .el-button-group {
  margin-right: 0;
}

.editor-toolbar .el-button.is-active {
  background-color: #409eff;
  color: #fff;
  border-color: #409eff;
}

.editor-toolbar .el-button.is-active:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.editor-toolbar .el-divider--vertical {
  margin: 0 8px;
}

.editor-content {
  min-height: 300px;
  padding: 16px;
  outline: none;
  line-height: 1.6;
  font-size: 14px;
  color: #303133;
  background-color: #fff;
}

.editor-content:empty:before {
  content: attr(placeholder);
  color: #c0c4cc;
  pointer-events: none;
}

.editor-content:focus {
  border-color: #409eff;
}

.editor-content h1,
.editor-content h2,
.editor-content h3 {
  margin: 16px 0 8px 0;
  font-weight: 600;
  color: #303133;
}

.editor-content h1 {
  font-size: 24px;
}

.editor-content h2 {
  font-size: 20px;
}

.editor-content h3 {
  font-size: 18px;
}

.editor-content p {
  margin: 8px 0;
}

.editor-content ul,
.editor-content ol {
  margin: 16px 0;
  padding-left: 20px;
  list-style-position: outside;
}

.editor-content ul {
  list-style-type: disc;
}

.editor-content ol {
  list-style-type: decimal;
}

.editor-content li {
  margin: 8px 0;
  padding-left: 8px;
  line-height: 1.6;
}

/* 嵌套列表样式 */
.editor-content ul ul,
.editor-content ol ol,
.editor-content ul ol,
.editor-content ol ul {
  margin: 4px 0;
  padding-left: 20px;
}

.editor-content ul ul {
  list-style-type: circle;
}

.editor-content ul ul ul {
  list-style-type: square;
}

.editor-content table {
  margin: 16px 0;
  border-collapse: collapse;
}

.editor-content td,
.editor-content th {
  padding: 8px;
  border: 1px solid #ddd;
  text-align: left;
}

.editor-content a {
  color: #409eff;
  text-decoration: none;
}

.editor-content a:hover {
  text-decoration: underline;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .editor-toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .editor-toolbar .el-button-group {
    justify-content: center;
  }
}
</style> 